﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:vischat/core/annotations/getx_route_enhanced.dart';
import 'package:vischat/modules/home/socialize/socialize_controller.dart';
import 'package:vischat/modules/home/socialize/widgets/conversation_item.dart';
import 'package:vischat/shared/widgets/top_search.dart';
import 'package:vischat/shared/widgets/view_list/view_list.dart';
import 'package:vischat/shared/widgets/view_list/view_list_controller.dart';

@GetXRoute('/socialize')
class SocializePage extends GetView<SocializeController> {
  const SocializePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            TopSearch(search: controller.search),
            Expanded(
              child: ViewList<SocializeController, V2TimConversation>(
                controller: controller,
                listBuilder:
                    () => CustomScrollView(
                      controller: controller.scrollController,
                      slivers: [
                        // 置顶会话区
                        _buildPinnedSection(),
                        // 普通会话区
                        _buildNormalSection(),
                        // 加载指示器
                        SliverToBoxAdapter(
                          child:
                              controller.state.value == ViewState.busy
                                  ? const Center(
                                    child: CircularProgressIndicator(),
                                  )
                                  : const SizedBox(),
                        ),
                      ],
                    ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPinnedSection() {
    final pinned =
        controller.list
            .where((c) => controller.isPinned(c.conversationID))
            .toList();

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (_, index) => ConversationItem(
          conversation: pinned[index],
          isPinned: true,
        ),
        childCount: pinned.length,
      ),
    );
  }

  Widget _buildNormalSection() {
    final normal =
        controller.list
            .where((c) => !controller.isPinned(c.conversationID))
            .toList();

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (_, index) => ConversationItem(
          conversation: normal[index],
          isPinned: false,
        ),
        childCount: normal.length,
      ),
    );
  }
}
